package com.demo.config;

import com.demo.filter.JWTAuthenFilter;
import com.demo.filter.JWTAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.demo.filter.JWTAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    //AuthenticationManager与AuthenticationManagerBuilder的关系
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
        authenticationManagerBuilder
            .userDetailsService(userDetailsService)
            .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/index","/user/login","/favicon.ico")
            .permitAll()
            .anyRequest()
            .authenticated()
           /* .and()
            //开启表单中的默认配置
            .formLogin()
                //配置自定义的登录页
            .loginPage("/user/login")
            .defaultSuccessUrl("/user/success")
            //loginProcessingUrl,必须和表单中action中的地址一致否则会404错误
            .loginProcessingUrl("/user/subLogin")
            .permitAll()*/
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthenFilter(authenticationManager()))
/*            .logout()
            .logoutUrl("/user/logout")
            .logoutSuccessUrl("/logouts")*/
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

}
